<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>Spring Boot WebSocket+广播式</title>
</head>

<body>
    <noscript>
        <h2 style="color:#ff0000">貌似你的浏览器不支持websocket</h2>
    </noscript>
    <div>
        <div>
            <button id="connect" onclick="connect()">连接</button>
            <button id="disconnect" onclick="disconnect();">断开连接</button>
        </div>
        <div id="conversationDiv">
            <label>输入你的名字</label> <input type="text" id="name" />
            <br>
            <label>输入消息</label> <input type="text" id="messgae" />
            <button id="send" onclick="send();">发送</button>
            <p id="response"></p>
        </div>
    </div>
    <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        var stompClient = null;
        var lockReconnect = false; //避免重复连接
        /**
         * 后台的服务在：https://github.com/yangxiying/testJava/tree/master/test-demo/src/main/java/com/yxycoding/demo/websock
         * 
         **/
        //gateway网关的地址
        // var host = "http://127.0.0.1:10001";
        var host = "http://jifen.xiaomy.net/prod-api";
        function setConnected(connected) {
            document.getElementById('connect').disabled = connected;
            document.getElementById('disconnect').disabled = !connected;
            document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
            $('#response').html();
        }
        // SendUser ***********************************************
        //https://stomp-js.github.io/stomp-websocket/codo/class/Client.html
        function connect() {
            //地址+端点路径，构建websocket链接地址,注意，对应config配置里的addEndpoint
            var socket = new SockJS(host + '/myUrl' + '?cookie=4567');
            stompClient = Stomp.over(socket);
            var headers = {};
            stompClient.connect(headers, function (frame) {
                setConnected(true);
                if (lockReconnect) return;
                lockReconnect = true;
                console.log('Connected:' + frame);
                //监听的路径以及回调,接收发给自己的消息
                var id11 = stompClient.subscribe('/user/queue/sendUser', function (response) {
                    showResponse(response.body);
                });
                console.log(id11)
                //监听的路径以及回调，接收全广播消息
                var id12 = stompClient.subscribe('/topic/sendTopic', function (response) {
                    showResponse(response.body);
                });

                stompClient.send("/sendIsConntion", {}, "my is readly");
                console.log(id12)

            }, function (err) {
                console.log('socket is err please confirm the wsrul is running!!!', err);
                disconnect();//断关连接


                //没连接上会一直重连，设置延迟避免请求过多 
                // setTimeout(function () {
                //     connect();
                //     lockReconnect = false;
                // }, 2000);

            });
        }
		/*
		function connect() {
            //地址+端点路径，构建websocket链接地址,注意，对应config配置里的addEndpoint
            var socket = new SockJS(host+'/myUrl');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                setConnected(true);
                console.log('Connected:' + frame);
                //监听的路径以及回调
                stompClient.subscribe('/topic/sendTopic', function(response) {
                    showResponse(response.body);
                });
            });
        }*/
        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
            }
            setConnected(false);
            lockReconnect = false;
            console.log("Disconnected");
        }
        function send() {
            var name = $('#name').val();
            var message = $('#messgae').val();
            /*//发送消息的路径,由客户端发送消息到服务端 
            stompClient.send("/sendServer", {}, message);
			*/
			/*// 发送给所有广播sendTopic的人,客户端发消息，大家都接收，相当于直播说话 注：连接需开启 /topic/sendTopic
			stompClient.send("/sendAllUser", {}, message);
			*/
			/* 这边需要注意，需要启动不同的前端html进行测试，需要改不同token ，例如 token=1234，token=4567
			* 然后可以通过写入name 为token  进行指定用户发送
			*/
            stompClient.send("/sendMyUser", {}, JSON.stringify({ name: name, message: message }));
        }
        function showResponse(message) {
            var response = $('#response');
            response.html(message);
        }
    </script>
</body>

</html>